import { Bcr } from "@/ecjrts/mode";
import { ModsInstance, useModule } from "@/func/createMod";
import { GetSomeTypeKey } from "@/ecjrts/tools/modHelper";

export interface BcrReadQRFnOpt<T> {
    mod?: T;
}

export type BcrMod = GetSomeTypeKey<Required<ModsInstance>, Bcr>;

export const ReadBarcode = async function (
    param: BcrReadQRFnOpt<BcrMod>,
    timeout: number,
) {
    const io = useModule();
    let { mod: modName = "bcr" } = param;
    let ctrl = io[modName];

    if (!ctrl) {
        throw new Error(`没有${modName}模块`);
    }

    let state = await ctrl.GetState();
    if (state.Result === "OK") {
        let ret = await ctrl.ReadBarcode(timeout);
        switch (ret.ret) {
            case "BarcodeRead":
                return ret;
                break;
            case "ReadBarcodeCancelled":
                return ret;
                break;
            case "Timeout":
                return ret;
                break;
            case "DeviceError":
                return ret;
                break;
            case "FatalError": ;
                return ret;
                break;
            default:
                return ret;
                break;
        }
    }
};

export const ResetBcr = async function (
    param: BcrReadQRFnOpt<BcrMod>,
) {
    const io = useModule();
    let { mod: modName = "bcr" } = param;
    let ctrl = io[modName];

    if (!ctrl) {
        throw new Error(`没有${modName}模块`);
    }

    let state = await ctrl.GetState();
    console.log(state);

    if (state.Result === "OK") {
        // let ret1 = await ctrl.Reset();
        let ret = await ctrl.Reset();
        // console.log(ret);
        switch (ret.ret) {
            case "ResetComplete":
                return ret;
                break;
            case "DeviceError":
                return ret;
                break;
            case "FatalError": ;
                return ret;
                break;
            default:
                return ret;
                break;
        }
    }
}

export const CancelReadBarcode = async function (
    param: BcrReadQRFnOpt<BcrMod>,
) {
    const io = useModule();
    let { mod: modName = "bcr" } = param;
    let ctrl = io[modName];

    if (!ctrl) {
        throw new Error(`没有${modName}模块`);
    }

    let state = await ctrl.GetState();
    console.log(state);

    if (state.Result === "OK") {
        // let ret1 = await ctrl.Reset();
        let ret = await ctrl.CancelReadBarcode();
        // console.log(ret);
        switch (ret.ret) {
            case "ReadBarcodeCancelled":
                return ret.ret;
                break;
            case "DeviceError":
                return ret.ret;
                break;
            case "FatalError": ;
                return ret.ret;
                break;
            default:
                return ret.ret;
                break;
        }
    }
}
